/*
 * $Id$
 */
package corejs;

/**
 *
 * @author myang
 */
public class Line implements Source {

   public static final char EOL = '\n';

   private final String _line;
   private final int _lineNum;

   private int _col;

   public Line(final String line) {
      this(1, line);
   }

   public Line(final int lineNum, final String s) {
      _lineNum = lineNum;
      _col = 0;
      _line = s;
   }

   @Override
   public int lineNum() {
      return _lineNum;
   }

   @Override
   public int col() {
      return _col;
   }

   @Override
   public char current() {
      return charAt(_col);
   }

   @Override
   public char next() {
      return charAt(++_col);
   }

   @Override
   public char prev() {
      return charAt(_col - 1);
   }

   @Override
   public char peek() {
      return charAt(1 + _col);
   }

   private char charAt(final int index) {
      return index < 0               ? 0 
         :   index >= _line.length() ? EOL 
         :                             _line.charAt(index);
   }

   @Override
   public String toString() {
      return String.format("%2d:%s", _lineNum, _line);
   }

   public static void main(final String... args) {
      final Line l = new Line("hello, world!");
      System.out.println(l.current());
      for (char c = l.next(); c != EOL; c = l.next()) {
         System.out.println(l.peek());
         System.out.println(c);
      }
      System.out.print(l.current());
      System.out.print(l.current());
      System.out.print(l.current());
   }

}
